<?php
/*
 * @Descripttion: 检查用户权限
 * @version: v1
 * @Author: Terry
 * @Date: 2021-10-05 16:19:18
 * @LastEditors: Terry
 * @LastEditTime: 2024-12-07 22:58:29
 */
declare (strict_types = 1);

namespace app\middleware;
use think\facade\Db;

class CheckAuth
{
    private $route;
    private $request;

    public function handle($request, \Closure $next){
        $route = strtolower($request->baseUrl());
        $route = array_filter(explode('/',$route));
        $route = join('/',$route);
        $this->route = '/'.$route;
        $this->request = $request;
        //检查用户权限
        $request->authWhere = ['projectCode'=> $this->request->prjCode];
        $res =  $this->checkAuth($next);
        // return $next($this->request);
        return $res;
    }


    /**
     * @Descripttion: 检查用户权限
     * @Author: Terry
     * @Date: 2021-10-05 16:22:02
     * @param {*}
     */    
    private function checkAuth($next){ 
        // 用户角色0=>普通用户 1=>管理员 2=>政府 3=>企业
        $userType = DB::connect('platform')->table('platform_userAccount')->where(['userUuid'=>$this->request->uuid])->value('role');
        //默认查询条件
        $where  = [
            'projectCode'=> $this->request->prjCode,
            'corpCode'=>$this->request->corpCode,
            'userUuid'=>$this->request->uuid,
            'status'=>1,
        ];

        //检查该权限是否模块权限
         $isModule = DB::connect('platform')->table('projectInfo_rule')
         ->alias('r')
         ->leftJoin('platform_module m','m.module  = r.module')
         ->where('r.method','like',"%".$this->route."%")
         ->field(['m.module','r.id'])
         ->find();
         if(empty($isModule['id'])) return result(FAIL,'','您无权访问该接口！');

        //非模块权限或管理员毋须带项目编码
        //非模块即平台（platform）或集成商(integrator)API权限
        //管理员=》所有均可用 无须判断
         if(empty($isModule['module']) || $userType==1) {
            $where['projectCode'] = '';
            $where['corpCode'] = '';
        }
        $permission = DB::connect('platform')->table('projectInfo_permission')->where($where)->field(['roleId','hiddenRuleId'])->find();
        if(empty($permission)) return result(FAIL,'','您无权访问该接口！');
        $authCheck  = strstr($permission['hiddenRuleId'],(string)$isModule['id']);
        if(!$authCheck){
            $authCheck = DB::connect('platform')->table('role')->where([
                ['id','=',$permission['roleId']],
                ['ruleId','like','%'.$isModule['id'].'%'],
            ])->value('id');
        }
        if(!$authCheck) return result(FAIL,'','您无权访问该接口！');
        if(!empty($isModule['module'])) $this->request->authWhere = $this->getAuthWhere($userType);
        return $next($this->request);
    }

    /**
     * @Descripttion:检查用户可查看/修改的内容 
     * @Author: Terry
     * @Date: 2021-10-13 17:51:41
     * @return  (int) 0=>普通用户 1=>管理员 2=>政府 3=>企业
     */
    private function getAuthWhere($userType){
        $authWhere = ['projectCode'=> $this->request->prjCode];
        //普通用户或企业帐号查看企业权限
        if(in_array($userType,[0,3])){
            $corptype = DB::connect('platform')->table('projectInfo_projectCorpInfo')->where([
                'projectCode'=> $this->request->prjCode,
                'corpCode'=>$this->request->corpCode,
            ])
            ->value('corpType');
            if($corptype != '009') $authWhere['corpCode'] = $this->request->corpCode;
        }
        if($userType == 4) unset($authWhere['corpCode']);

        $method = $this->request->method();
        $data = $this->request->$method();
        //上传的数据有corpCode 说明是添加/修改/带搜索条件的查找
        if(isset($data['corpCode'])&&!empty($data['corpCode'])){
            if(isset($authWhere['corpCode'])){
                //如果是分包单位，无论查找还是搜索只能是自己
                $this->request->authData = ['corpCode'=>$authWhere['corpCode']];
            }else{
                //如果是总包单位，传什么就用什么
                $authWhere['corpCode'] = $data['corpCode'];    
            }
        }
        return $authWhere;
    }
}
